package main

import (
	"CampusNetworkTools/config"
	"CampusNetworkTools/core"
	"CampusNetworkTools/win_bridge"
	"context"
	"os"
	"os/exec"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

func (a *App) SetAppConfig(s config.Config) error {
	err := config.WriteConfig(s)
	if err != nil {
		return err
	}

	return nil
}

func (a *App) InitAppConfig() error {
	return config.InitConfig()
}

func (a *App) GetAppConfig() (string config.Config) {
	return config.AppConfig
}

func (a *App) AuthNMXX(userId, passwd string) (string, error) {
	return core.LoginNMXX(userId, passwd)
}

func (a *App) AuthYYJSWIFI(userId, passwd string) (string, error) {
	return core.LoginYYJSWIFI(userId, passwd)
}

func (a *App) CreateTask() error {
	tasker, err := win_bridge.NewTasker()
	if err != nil {
		return err
	}
	defer tasker.Release()

	err = tasker.CreateTask()
	if err != nil {
		return err
	}

	return nil
}

func (a *App) GetTaskStateOK() bool {
	tasker, err := win_bridge.NewTasker()
	if err != nil {
		return false
	}
	defer tasker.Release()

	task, err := tasker.GetTask()
	if err != nil {
		return false
	}

	return task.Enabled
}

func (a *App) DeleteTask() error {
	tasker, err := win_bridge.NewTasker()
	if err != nil {
		return err
	}
	defer tasker.Release()
	return tasker.DeleteTask()
}

func (a *App) OpenWindowsTasker() error {
	return exec.Command("cmd", "/c", "start", "taskschd").Start()
}

func (a *App) GetLogContent() (string, error) {
	content, err := os.ReadFile(config.ExeDir() + "/app.log")
	if err != nil {
		return "", err
	}

	return string(content), nil
}
